package com.ktg.mes.pro.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ktg.common.constant.UserConstants;
import com.ktg.common.core.domain.AjaxResult;
import com.ktg.common.exception.ServiceException;
import com.ktg.common.utils.DateUtils;
import com.ktg.common.utils.StringUtils;
import com.ktg.mes.pro.domain.*;
import com.ktg.mes.pro.service.*;
import com.ktg.mes.rec.domain.*;
import com.ktg.mes.rec.service.*;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktg.mes.pro.mapper.ProProcessMapper;

import javax.validation.constraints.NotNull;

/**
 * 生产工序Service业务层处理
 *
 * @author yinjinlu
 * @date 2022-05-11
 */
@Service
public class ProProcessServiceImpl implements IProProcessService
{
    @Autowired
    private ProProcessMapper proProcessMapper;
    @Autowired
    private IProRouteProcessService proRouteProcessService;
    @Autowired
    private IProTaskService proTaskService;

    @Autowired
    IRecLnspectionRecordService recLnspectionRecordService;

    @Autowired
    private IProRouteProductService proRouteProductService;

    /**
     * 查询生产工序
     *
     * @param processId 生产工序主键
     * @return 生产工序
     */
    @Override
    public ProProcess selectProProcessByProcessId(Long processId)
    {
        return proProcessMapper.selectProProcessByProcessId(processId);
    }

    /**
     * 查询生产工序列表
     *
     * @param proProcess 生产工序
     * @return 生产工序
     */
    @Override
    public List<ProProcess> selectProProcessList(ProProcess proProcess)
    {
        return proProcessMapper.selectProProcessList(proProcess);
    }

    /**
     * 检查工序编码是否唯一
     * @param proProcess
     * @return
     */
    @Override
    public String checkProcessCodeUnique(ProProcess proProcess) {
        ProProcess process = proProcessMapper.checkProcessCodeUnique(proProcess);
        Long processId = proProcess.getProcessId()==null?-1L:proProcess.getProcessId();
        if(StringUtils.isNotNull(process) && process.getProcessId().longValue() != processId.longValue()){
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }


    /**
     * 检查工序名称是否唯一
     * @param proProcess
     * @return
     */
    @Override
    public String checkProcessNameUnique(ProProcess proProcess) {
        ProProcess process = proProcessMapper.checkProcessNameUnique(proProcess);
        Long processId = proProcess.getProcessId()==null?-1L:proProcess.getProcessId();
        if(StringUtils.isNotNull(process) && process.getProcessId().longValue() != processId.longValue()){
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增生产工序
     *
     * @param proProcess 生产工序
     * @return 结果
     */
    @Override
    public int insertProProcess(ProProcess proProcess)
    {
        proProcess.setCreateTime(DateUtils.getNowDate());
        return proProcessMapper.insertProProcess(proProcess);
    }

    /**
     * 修改生产工序
     *
     * @param proProcess 生产工序
     * @return 结果
     */
    @Override
    public int updateProProcess(ProProcess proProcess)
    {
        proProcess.setUpdateTime(DateUtils.getNowDate());
        return proProcessMapper.updateProProcess(proProcess);
    }

    /**
     * 批量删除生产工序
     *
     * @param processIds 需要删除的生产工序主键
     * @return 结果
     */
    @Override
    public int deleteProProcessByProcessIds(Long[] processIds)
    {
        return proProcessMapper.deleteProProcessByProcessIds(processIds);
    }

    /**
     * 删除生产工序信息
     *
     * @param processId 生产工序主键
     * @return 结果
     */
    @Override
    public int deleteProProcessByProcessId(Long processId)
    {
        return proProcessMapper.deleteProProcessByProcessId(processId);
    }

    private ProProcess encapsulation(ProProcess process,RecLnspectionRecord item,StringBuilder sb ){

        String dicText = item.getDicText();
        Map<String,Object> map = JSONObject.parseObject(dicText, Map.class);
        if(StringUtils.isNotNull(map.get("开始时间"))){
            sb.append(map.get("开始时间")).append(" ");
        }else{
            sb.append(map.get("检测时间")).append(" ");
        }

        //    机台
        process.setWorkstationCode(item.getWorkstationCode());
        process.setToolTypeName(map.get("桶号").toString()); // 桶号
        process.setOperator(item.getCreateBy()); // 操作员
        map.remove("桶号");
        map.remove("工作任务");
        map.remove("开始时间");
        map.remove("检测时间");
        for (Map.Entry<String,Object> entry : map.entrySet()){
            sb.append(entry.getKey()).append(":").append(entry.getValue()).append(" ");
        }
        process.setOperationProcess(sb.toString());
        return process;
    }

//    /**
//     * 查询打印数据(流程)
//     * @param itemId
//     * @return
//     */
//    @SneakyThrows
//    @Override
//    public List<ProProcess> selectPrintData(Long itemId,Long workorderId,Long taskId) {
//        List<ProRouteProcess> processList = proRouteProcessService.selectPrintData(itemId);
//        //工艺流程 工序id集合
//        Long[] processIds = processList.stream().map(ProRouteProcess::getProcessId).toArray(Long[]::new);
//        //工序集合
//        List<ProProcess> processes = proProcessMapper.selectPrintData(processIds);
//        //工序记录集合
//        List<RecLnspectionRecord> list = recLnspectionRecordService.list(new LambdaQueryWrapper<RecLnspectionRecord>().eq(RecLnspectionRecord::getTaskId, taskId));
//
//
//        StringBuilder sb = new StringBuilder();
//        ArrayList<ProProcess> proProcesses = new ArrayList<>();
//        ArrayList<RecLnspectionRecord> list_repeat = new ArrayList<>();
//
//        int index = 0;
//        for (ProProcess process : processes) {
//            for (RecLnspectionRecord item : list) {
//                if(process.getProcessId().longValue() == item.getProcessesId().longValue()) {
//                    ProProcess pro = this.encapsulation(process, item, sb);
//                    list_repeat.add(item);
//                    proProcesses.add(pro);
//                    index++;
//                    sb = new StringBuilder();
//                }
//            }
//            //当前工序没有记录
//            if(index ==  0){
//                proProcesses.add(process);
//            }
//            index = 0;
//        }
//        // List<RecLnspectionRecord> collect = Stream.of(list, list_repeat).flatMap(Collection::stream).distinct().collect(Collectors.toList());
//
//        List<RecLnspectionRecord> collect = list.stream().filter(item -> !list_repeat.contains(item)).collect(Collectors.toList());
//        // 产品工艺没有的工序流程
//        if(!collect.isEmpty()){
//            for (RecLnspectionRecord item : collect) {
//                ProProcess proProcess1 = proProcessMapper.selectProProcessByProcessId(item.getProcessesId());
//                ProProcess process = this.encapsulation(proProcess1, item, sb);
//                proProcesses.add(process);
//                sb = new StringBuilder();
//            }
//        }
//        return proProcesses;
//    }
}
